// 导入Vue框架
import Vue from 'vue';
import VueRouter from 'vue-router';
import Vuex from 'vuex';

// 导入app.vue组件
import App from './app.vue';
import VueBus from './vue-bus';
import VueAjax from './vue-ajax';

Vue.use(VueRouter);
Vue.use(Vuex);
Vue.use(VueBus);
Vue.use(VueAjax);

const Routers = [{
        path: '/index',
        meta: {
            title: '首页',
        },
        component: (resolve) => require(['./router/views/index.vue'], resolve)
    },
    {
        path: '/about',
        meta: {
            title: '关于',
        },
        component: (resolve) => require(['./router/views/about.vue'], resolve)
    },
    {
        path: '/user/:id',
        meta: {
            title: '个人主页',
        },
        component: (resolve) => require(['./router/views/user.vue'], resolve)
    },
    {
        path: '*',
        redirect: '/index'
    }
];
const RouterConfig = {
    mode: 'history',
    routes: Routers
};
const router = new VueRouter(RouterConfig);
router.beforeEach((to, form, next) => {
    // 标题设置
    window.document.title = to.meta.title;
    next();
})
router.afterEach((to, form, next) => {
    // 返回页面顶部
    window.scrollTo(0, 0);
})

const store = new Vuex.Store({
    state: {
        count: 0,
        list: [1, 5, 8, 10, 30, 50]
    },
    mutations: {
        /**
         * ES6语法，参数可带默认值，当没有传入该参数时，将使用默认参数值
         */
        increment(state, n = 1) {
            state.count += n;
        },
        decrease(state) {
            state.count--;
        }
    },
    getters: {
        filteredList: state => {
            return state.list.filter(item => item < 10);
        },
        listCount: (state, getters) => {
            return getters.filteredList.length;
        }
    },
	actions: {
		asyncIncrement(context){
			return new Promise(resolve => {
				setTimeout(()=>{
					context.commit('increment');
					resolve();
				},1000)
			})
		}
	}
})

// 创建Vue根实例
new Vue({
    el: '#app',
    /**
     * =>是箭头函数
     * render: h => h(App)等同于:
     * render: function(h){
     *	return h(App) 
     * }
     */
    render: h => h(App),
    router: router,
    store: store
})
